<?php
namespace Admin\Controller;
use Lib\Api\AgentApi;
use Lib\Api\RechargeWithdrawalsApi;
use Lib\Api\UserApi;
use Lib\Utils\PayUtils;
use Think\Controller;
class RechargeWithdrawalsController extends Controller {


    public function index(){
        $this->display();
    }

    public function query() {
        $modelObj = M();
        $organization_id = session("admin_id");
        $min_date = $modelObj
            ->table("fs_recharge_withdrawals a")
            ->field('DATE_FORMAT(a.datetime, "%Y-%m-%d") as datetime')
            ->join("left join fs_user_belong b on b.user_id = a.user_id")
            ->where(array("b.organization_id"=>$organization_id, "a.audit_state"=>array("neq", 2)))->page(1,1)->find();

        $d = date('Y-m-d H:i');
        if (!empty($min_date)) {
            $d = $min_date['datetime'];
        }

        $this->assign('d', $d);
        $this->display();
    }

    public function audit() {
        $modelObj = M();
        $organization_id = session("admin_id");
        $min_date = $modelObj
            ->table("fs_recharge_withdrawals a")
            ->field('DATE_FORMAT(a.datetime, "%Y-%m-%d") as datetime')
            ->join("left join fs_user_belong b on b.user_id = a.user_id")
            ->where(array("b.organization_id"=>$organization_id, "a.audit_state"=>array("eq", 2)))->page(1,1)->find();

        $d = date('Y-m-d H:i');
        if (!empty($min_date)) {
            $d = $min_date['datetime'];
        }

        $this->assign('d', $d);

        $this->display();
    }

    public function toQuery(){
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];

        // var_dump($page_num);

        $data_cycle = $_POST['data_cycle'];
        $nick_name = $_POST['nick_name'];
        $mobile_phone = $_POST['mobile_phone'];
        $audit_state = $_POST['audit_state'];
        $type = $_POST['type'];
		$source = $_POST['source'];
		$remark = $_POST['remark'];

        // , "b.audit_state"=>array("eq", 2)

        $organization_id = session("admin_id");

        $field = "a.*, if(a.type=1, money, 0) recharge, if(a.type=2, money, 0) withdrawals, u.nick_name, u.mobile_phone, u.balance, c.name as audit_admin";

        $left = 'left join fs_user u on u.id = a.user_id';
        $left .= ' left join fs_user_belong b on b.user_id = u.id and b.state = 1';
        $left .= ' left join fs_organization c on c.id = a.audit_organization_id';

        // $map = array();

        if ($nick_name != "") {
            $where['u.nick_name']  = array('like', '%'.$nick_name.'%');
        }
        if ($mobile_phone != "") {
            $where['u.mobile_phone']  = array('like', '%'.$mobile_phone.'%');
        }
        if ($type > 0) {
            $where["a.type"] = array("eq", $type);
        }
        if ($source > 0) {
            $where["a.source"] = array("eq", $source);
        }
		if ($remark != '') {
            $where["a.remark"] = array("eq", $remark);
        }
		
        /*if (count($map) > 0) {
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
        }*/
        $where["b.organization_id"] = $organization_id;
        $where["a.audit_state"] = array('exp', ' IN ('.$audit_state.')');

        if ($data_cycle != "") {
            $search_date = explode('/', $data_cycle);
            $begin_date = $search_date[0];
            $end_date = $search_date[1];

            $where['DATE_FORMAT(a.datetime, "%Y-%m-%d")'] = array(array('egt', $begin_date), array('elt',$end_date));
        }

        $where['DATE_FORMAT(b.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")');

        // $where, $left='', $field='*', $page_num=1, $page_size=15, $order='', $group=''
        $list = RechargeWithdrawalsApi::getList($where, $left, $field, $page_num, $page_size, 'a.datetime desc', "a.out_trade_no");

        $left = 'left join fs_user u on u.id = a.user_id';
        $left .= ' left join fs_user_belong b on b.user_id = a.user_id and b.state = 1';
        $left .= ' left join fs_organization c on c.id = a.audit_organization_id';
        $total = RechargeWithdrawalsApi::getTotal($where, $left);
        $user_list = pageHelper($page_size, $page_num, $list, $total);
        $rel['data'] = $user_list;

        $model = M();
        $sum_field = "ifnull(sum(if(a.type=1, a.money, 0)),0) as recharge, ifnull(sum(if(a.type=2, a.money, 0)),0) withdrawals";
        $sum = $model->table('fs_recharge_withdrawals a')
            ->field($sum_field)
            ->join($left)
            ->where($where)
            ->select();
        $rel['total_recharge'] = sprintf("%.2f", $sum[0]["recharge"]);
        $rel['total_withdrawals'] = sprintf("%.2f", $sum[0]["withdrawals"]);

        $this->ajaxReturn($rel);
    }

    public function subAuditRechargeOrWithdrawals() {
        $organization_id = session("admin_id");
        $id = $_POST["id"];
        $audit_state = $_POST["audit_state"];
        $auto = $_POST['auto'];
        $userRechargeWithdrawals = RechargeWithdrawalsApi::getInfo(array("id"=>$id, "audit_state"=>2));
        if (!empty($userRechargeWithdrawals)) {
            $user = UserApi::getInfoByCondition(array('a.id'=>$userRechargeWithdrawals["user_id"]), "", 'a.id, a.balance, a.freeze_balance, a.mobile_phone');
            $money = floatval($userRechargeWithdrawals["money"]);
            $fee = 0;
            $rel = false;
            if ($userRechargeWithdrawals["type"] == 1) {
                // 充值
                if ($audit_state == 1) {
                    $balance = $money-$fee;
                    $user['balance'] = array('exp','balance+'.$balance);
                    $rel = UserApi::save($user);
                } else if ($audit_state == 3) {
                    $rel = true;
                }
            } else {
				if ($userRechargeWithdrawals["source"] == 1) {
					// 用户余额提现
					if ($audit_state == 1) {
						$model = M("Sys");
						$data = $model->field("withdrawals_fee")->where(array('id' => 1))->find();
						$fee = $money * (floatval($data['withdrawals_fee'])/100);
						$withdrawals_money = $money-$fee;
						$flag = true;
						if ($auto == 1) {
							$flag = false;
							// $user = UserApi::getUserInfo($userRechargeWithdrawals["user_id"]);
							if (!empty($userRechargeWithdrawals['bank_name']) && !empty($userRechargeWithdrawals['bank_no']) && !empty($userRechargeWithdrawals['cardholder']) && !empty($userRechargeWithdrawals['identity'])) {
								$timestamp = date("YmdHis");
								$pay_memberid = C('__PAYNO__');             //商户ID
								$pay_notifyurl = C("__PAYCALLSERVICE__");   //异步回掉地址
								$tranId = $userRechargeWithdrawals['out_trade_no'];    //订单号
								$amount = $withdrawals_money*100;
								if ($amount > 0) {
									$str = '<?xml version="1.0" encoding="utf-8" standalone="no"?><message application="ReceivePay" merchantId="'.$pay_memberid.'" tranId="'.$tranId.'" timestamp="'.$timestamp.'" receivePayNotifyUrl="'.$pay_notifyurl.'" accountProp="0" receivePayType="1" bankGeneralName="'.$userRechargeWithdrawals['bank_name'].'" accNo="'.$userRechargeWithdrawals['bank_no'].'" accName="'.$userRechargeWithdrawals['cardholder'].'" amount="'.$amount.'" credentialType="01" credentialNo="'.$userRechargeWithdrawals['identity'].'" tel="'.$user['mobile_phone'].'" version="1.0.1" />';
									$msg_str = PayUtils::getStrMsg($str);

									$gateway_url = C('__PAYDOMAIN__');   //提交地址
									$ch = curl_init();
									curl_setopt($ch, CURLOPT_URL, $gateway_url);
									curl_setopt($ch, CURLOPT_POST, true);
									curl_setopt($ch, CURLOPT_POSTFIELDS, $msg_str);
									curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
									curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
									curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
									$result = curl_exec($ch);
									$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
									curl_close($ch);
									/******异步通知，请参考下面过程******/
									$tmp = explode("|", $result);
									$resp_xml = base64_decode($tmp[0]);
									$resp_sign = $tmp[1];
									$fp = fopen('aaaa.txt','w+');
									fwrite($fp,$resp_xml);
									fclose($fp);
									if(PayUtils::verity(md5($resp_xml,true),$resp_sign)) { //验签
										$postObj = simplexml_load_string($resp_xml);
										if ($postObj['respCode'] == '000') {
											// $rel_data['msg'] = $postObj['respDesc'];
											// $rel_data['code'] = -1;
											$flag = true;
										}
									}
								}
							} else {
								$flag = false;
							}
						}

						if ($flag == true) {
							$user['freeze_balance'] = array('exp','freeze_balance-'.$money);
							$user['withdrawals'] = array('exp','withdrawals+'.$money);
							// $user['balance'] = array('exp','balance-'.$money);
							$rel = UserApi::save($user);

							$user_data = UserApi::getInfo(array("id"=>$userRechargeWithdrawals["user_id"]), "balance");

							$modelObj = M("TradeDetail");
							$params = array("user_id"=>$userRechargeWithdrawals["user_id"], "deal_user_id"=>0, "out_trade_no"=>$userRechargeWithdrawals["out_trade_no"], "type"=>7, "money"=>-$money,
								"fee_money"=>$fee, "other_money"=>0, "balance"=>$user_data['balance'], "source"=>7, "remark"=>"提现审核通过",
								"state"=>1, "datetime"=>date('Y-m-d H:i:s'));
							$modelObj->add($params);
						}
					} else if ($audit_state == 3) {
						$user['balance'] = array('exp','balance+'.$money);
						$user['freeze_balance'] = array('exp','freeze_balance-'.$money);
						$rel = UserApi::save($user);

						$user_data = UserApi::getInfo(array("id"=>$userRechargeWithdrawals["user_id"]), "balance");

						$modelObj = M("TradeDetail");
						$params = array("user_id"=>$userRechargeWithdrawals["user_id"], "deal_user_id"=>0, "out_trade_no"=>$userRechargeWithdrawals["out_trade_no"], "type"=>8, "money"=>-$money,
							"fee_money"=>0, "other_money"=>0, "balance"=>$user_data['balance'], "source"=>7, "remark"=>"提现审核不通过",
							"state"=>1, "datetime"=>date('Y-m-d H:i:s'));
						$modelObj->add($params);
					}
				} else {
                    // 经纪人收益提现
                    $agent = AgentApi::getInfo(array('b.id'=>$userRechargeWithdrawals["user_id"]), "left join fs_user b on b.agent_id = a.id", 'a.id');
                    $rel = false;
                    if ($userRechargeWithdrawals["type"] == 2) {
                        if ($audit_state == 1) {
                            $model = M("Sys");
                            $data = $model->field("withdrawals_fee")->where(array('id' => 1))->find();
                            $fee = $money * (floatval($data['withdrawals_fee'])/100);
                            $withdrawals_money = $money-$fee;
                            $flag = true;
                            if ($auto == 1) {
                                $flag = false;
                                // $user = UserApi::getUserInfo($userRechargeWithdrawals["user_id"]);
                                if (!empty($userRechargeWithdrawals['bank_name']) && !empty($userRechargeWithdrawals['bank_no']) && !empty($userRechargeWithdrawals['cardholder']) && !empty($userRechargeWithdrawals['identity'])) {
                                    $timestamp = date("YmdHis");
                                    $pay_memberid = C('__PAYNO__');             //商户ID
                                    $pay_notifyurl = C("__PAYCALLSERVICE__");   //异步回掉地址
                                    $tranId = $userRechargeWithdrawals['out_trade_no'];    //订单号
                                    $amount = $withdrawals_money*100;
                                    if ($amount > 0) {
                                        $str = '<?xml version="1.0" encoding="utf-8" standalone="no"?><message application="ReceivePay" merchantId="'.$pay_memberid.'" tranId="'.$tranId.'" timestamp="'.$timestamp.'" receivePayNotifyUrl="'.$pay_notifyurl.'" accountProp="0" receivePayType="1" bankGeneralName="'.$userRechargeWithdrawals['bank_name'].'" accNo="'.$userRechargeWithdrawals['bank_no'].'" accName="'.$userRechargeWithdrawals['cardholder'].'" amount="'.$amount.'" credentialType="01" credentialNo="'.$userRechargeWithdrawals['identity'].'" tel="'.$user['mobile_phone'].'" version="1.0.1" />';
                                        $msg_str = PayUtils::getStrMsg($str);

                                        $gateway_url = C('__PAYDOMAIN__');   //提交地址
                                        $ch = curl_init();
                                        curl_setopt($ch, CURLOPT_URL, $gateway_url);
                                        curl_setopt($ch, CURLOPT_POST, true);
                                        curl_setopt($ch, CURLOPT_POSTFIELDS, $msg_str);
                                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                                        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                                        $result = curl_exec($ch);
                                        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                                        curl_close($ch);
                                        /******异步通知，请参考下面过程******/
                                        $tmp = explode("|", $result);
                                        $resp_xml = base64_decode($tmp[0]);
                                        $resp_sign = $tmp[1];
                                        if(PayUtils::verity(md5($resp_xml,true),$resp_sign)) { //验签
                                            $postObj = simplexml_load_string($resp_xml);
                                            if ($postObj['respCode'] == '000') {
                                                $fp = fopen('aaaa.txt','w+');
                                                fwrite($fp,$resp_xml);
                                                fclose($fp);
                                                // $rel_data['msg'] = $postObj['respDesc'];
                                                // $rel_data['code'] = -1;
                                                $flag = true;
                                            }
                                        }
                                    }
                                }
                            }

                            if ($flag == true) {
                                $agent['freeze_money'] = array('exp', 'freeze_money-' . $money);
                                $agent['settlement_money'] = array('exp', 'settlement_money+' . $money);
                                $rel = AgentApi::saveByCondition(array("id" => $agent['id']), $agent);

                                $agent_data = AgentApi::getInfo(array("a.id" => $agent['id']), "", "a.balance");

                                $modelObj = M("TradeDetail");
                                $params = array("user_id" => $userRechargeWithdrawals["user_id"], "deal_user_id" => 0, "out_trade_no" => $userRechargeWithdrawals["out_trade_no"], "type" => 7, "money" => -$money,
                                    "fee_money" => $fee, "other_money" => 0, "balance" => $agent_data['balance'], "source" => 8, "remark" => "提现审核通过",
                                    "state" => 1, "datetime" => date('Y-m-d H:i:s'));
                                $modelObj->add($params);
                            }
                        } else if ($audit_state == 3) {
                            $agent['freeze_money'] = array('exp','freeze_money-'.$money);
                            $agent['balance'] = array('exp','balance+'.$money);
                            $rel = AgentApi::saveByCondition(array("id"=>$agent['id']), $agent);

                            $agent_data = AgentApi::getInfo(array("a.id"=>$agent['id']), "", "a.balance");

                            $modelObj = M("TradeDetail");
                            $params = array("user_id"=>$userRechargeWithdrawals["user_id"], "deal_user_id"=>0, "out_trade_no"=>$userRechargeWithdrawals["out_trade_no"], "type"=>8, "money"=>-$money,
                                "fee_money"=>0, "other_money"=>0, "balance"=>$agent_data['balance'], "source"=>8, "remark"=>"提现审核不通过",
                                "state"=>1, "datetime"=>date('Y-m-d H:i:s'));
                            $modelObj->add($params);
                        }
                    }
                }
                
            }
            if ($rel) {
                /*$organization = OrganizationApi::getInfoByCondition(array('a.id'=>$userRechargeWithdrawals["organization_id"]), "", 'a.id, a.balance');
                $params = array("organization_id"=>$organization["id"], "money"=>$money, "fee"=>$fee, "balance"=>$organization["balance"],
                    "type"=>$userRechargeWithdrawals["type"], "out_trade_no"=>$userRechargeWithdrawals["out_trade_no"], "datetime"=>date('Y-m-d H:i:s'));
                $modelObj = M("OrganizationTradeDetail");
                $modelObj->add($params); */

                $userRechargeWithdrawals["audit_state"] = $audit_state;
                $userRechargeWithdrawals["audit_organization_id"] = $organization_id;
                $userRechargeWithdrawals["audit_date"] = date('Y-m-d H:i:s');

                RechargeWithdrawalsApi::save($userRechargeWithdrawals);

                $rel_data['code'] = 1;

            } else {
                $rel_data['code'] = 2;
            }

            $this->ajaxReturn($rel_data);
        }
    }
}